/*
 * @Date: 2024-05-10 14:36:18
 * @LastEditTime: 2024-05-13 15:18:09
 * @Description:
 * @FilePath: \gas-report\src\utils\index.ts
 */

import { jsonp } from "vue-jsonp";
import { message } from "./message";

const KEY = "OUEBZ-7TEWB-UATUY-JFZPV-6XFI3-IFB3T";

/**
 * 时间转为秒
 * @param time 时间(00:00:00或者00:00)
 * @returns {number} 时间戳（单位：秒）
 */
export const time_to_sec = (time: string) => {
  let s = 0;
  let hour = "";
  let min = "";
  let sec = "";
  if (time.split(":").length == 3) {
    // 时分秒
    hour = time.split(":")[0];
    min = time.split(":")[1];
    sec = time.split(":")[2];
  } else if (time.split(":").length == 2) {
    // 分秒
    min = time.split(":")[0];
    sec = time.split(":")[1];
  }

  s = Number(hour * 3600) + Number(min * 60) + Number(sec);

  return s;
};

/**
 * @param {*} fn 要执行的函数
 * @param {*} interval 时间间隔
 * @returns
 */
export const throttle = (fn: any, interval: number) => {
  // 1.记录上一次的开始时间
  let lastTime = 0;

  // 2.事件触发时, 真正执行的函数
  const _throttle = function () {
    // 2.1.获取当前事件触发时的时间
    const nowTime = new Date().getTime();

    // 2.2.使用当前触发的时间和之前的时间间隔以及上一次开始的时间, 计算出还剩余多长时间需要去触发函数
    const remainTime = interval - (nowTime - lastTime);
    //第一次会执行，原因是nowTime刚开始是一个很大的数字，结果为负数
    //若最后一次没能满足条件，不会执行
    if (remainTime <= 0) {
      // 2.3.真正触发函数
      fn();
      // 2.4.保留上次触发的时间
      lastTime = nowTime;
    }
  };

  return _throttle;
};

/**
 * @description 转换84坐标至GCJ02
 * @returns [lng,lat]
 */
export const transformFromWGS84ToGCJ02 = (lng: number, lat: number) => {
  const a = 6378245.0; // a: 纬度方向上的克拉索夫斯基椭球长半径,单位：米
  const ee = 0.00669342162296594323; // ee: 克拉索夫斯基椭球扁率

  // 纬度转换
  let dLat = transformLat(lng - 105.0, lat - 35.0);
  let dLng = transformLng(lng - 105.0, lat - 35.0);
  let radLat = (lat / 180.0) * Math.PI;
  let magic = Math.sin(radLat);
  magic = 1 - ee * magic * magic;
  let sqrtMagic = Math.sqrt(magic);
  dLat = (dLat * 180.0) / (((a * (1 - ee)) / (magic * sqrtMagic)) * Math.PI);
  dLng = (dLng * 180.0) / ((a / sqrtMagic) * Math.cos(radLat) * Math.PI);
  let mgLat = lat + dLat;
  let mgLng = lng + dLng;

  return [mgLng, mgLat];
};

function transformLat(x: number, y: number) {
  let ret =
    -100.0 +
    2.0 * x +
    3.0 * y +
    0.2 * y * y +
    0.1 * x * y +
    0.2 * Math.sqrt(Math.abs(x));
  ret +=
    ((20.0 * Math.sin(6.0 * x * Math.PI) + 20.0 * Math.sin(2.0 * x * Math.PI)) *
      2.0) /
    3.0;
  ret +=
    ((20.0 * Math.sin(y * Math.PI) + 40.0 * Math.sin((y / 3.0) * Math.PI)) *
      2.0) /
    3.0;
  ret +=
    ((160.0 * Math.sin((y / 12.0) * Math.PI) +
      320 * Math.sin((y * Math.PI) / 30.0)) *
      2.0) /
    3.0;
  return ret;
}

function transformLng(x: number, y: number) {
  let ret =
    300.0 +
    x +
    2.0 * y +
    0.1 * x * x +
    0.1 * x * y +
    0.1 * Math.sqrt(Math.abs(x));
  ret +=
    ((20.0 * Math.sin(6.0 * x * Math.PI) + 20.0 * Math.sin(2.0 * x * Math.PI)) *
      2.0) /
    3.0;
  ret +=
    ((20.0 * Math.sin(x * Math.PI) + 40.0 * Math.sin((x / 3.0) * Math.PI)) *
      2.0) /
    3.0;
  ret +=
    ((150.0 * Math.sin((x / 12.0) * Math.PI) +
      300.0 * Math.sin((x / 30.0) * Math.PI)) *
      2.0) /
    3.0;
  return ret;
}
// Function to compress the image
const compressImage = (canvas, quality = 0.9) => {
  return new Promise((resolve) => {
    canvas.toBlob(
      (blob) => {
        if (blob.size <= 1 * 1024 * 1024 || quality <= 0.1) {
          resolve(blob);
        } else {
          resolve(compressImage(canvas, quality - 0.1));
        }
      },
      "image/jpeg",
      quality
    );
  });
};
const getCurrentDateTime = () => {
    const now = new Date();
    const year = now.getFullYear();
    const month = (now.getMonth() + 1).toString().padStart(2, '0');
    const day = now.getDate().toString().padStart(2, '0');
    const hours = now.getHours().toString().padStart(2, '0');
    const minutes = now.getMinutes().toString().padStart(2, '0');
    const seconds = now.getSeconds().toString().padStart(2, '0');
    return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`;
};
export const addWatermarkAndCompressImage = (filee, account?, time?) => {
  message();
  // 企业不用加水印
  const isEnt = uni.getStorageSync("userOrgType") == "企业";
  let file = filee.file;
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.src = URL.createObjectURL(file);
    img.onload = async () => {
      const canvas = document.createElement("canvas");
      const ctx = canvas.getContext("2d");
      canvas.width = img.width;
      canvas.height = img.height;

      // Draw the original image
      ctx.drawImage(img, 0, 0);

      // Analyze the image to determine the average background color
      const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
      const data = imageData.data;

      let r = 0,
        g = 0,
        b = 0;
      for (let i = 0; i < data.length; i += 4) {
        r += data[i];
        g += data[i + 1];
        b += data[i + 2];
      }
      r = Math.floor(r / (data.length / 4));
      g = Math.floor(g / (data.length / 4));
      b = Math.floor(b / (data.length / 4));

      // Determine if the background is light or dark
      const brightness = (r * 299 + g * 587 + b * 114) / 1000;
      let watermarkColor, shadowColor;
      if (brightness > 200) {
        watermarkColor = "rgba(0, 0, 0, 0.7)"; // Very light background
        shadowColor = "rgba(255, 255, 255, 0.7)";
      } else if (brightness > 128) {
        watermarkColor = "rgba(0, 0, 0, 0.7)"; // Light background
        shadowColor = "rgba(255, 255, 255, 0.7)";
      } else if (brightness > 64) {
        watermarkColor = "rgba(255, 255, 255, 0.7)"; // Dark background
        shadowColor = "rgba(0, 0, 0, 0.7)";
      } else {
        watermarkColor = "rgba(255, 255, 255, 0.9)"; // Very dark background
        shadowColor = "rgba(0, 0, 0, 0.9)";
      }

      // Set watermark color and shadow
      ctx.fillStyle = watermarkColor;
      ctx.shadowColor = shadowColor;
      ctx.shadowOffsetX = 2;
      ctx.shadowOffsetY = 2;
      ctx.shadowBlur = 2;

      // Calculate font size based on image dimensions
      const fontSize = Math.max(22, Math.min(canvas.width, canvas.height) / 30);
      ctx.font = `bold ${fontSize}px serif`;
      ctx.textAlign = "left";
      ctx.textBaseline = "bottom";
      
      let lat = '';
      let lon = '';
      const locLat= uni.getStorageSync("location")
      if(locLat) {
        lat = JSON.parse(locLat)["latitude"];
        lon = JSON.parse(locLat)["longitude"];
      }
      if (!isEnt) {
        if(lat && lon) {
          // 政府
          try {
            // Add account, time, and address
            getAddress(lat, lon).then((res) => {
              let address = res;
              console.log(address);
              lat && ctx.fillText(`经纬度: ${lon},${lat}`, 10, canvas.height - 320);
              address && ctx.fillText(`地址: ${address}`, 10, canvas.height - 220);
              time && ctx.fillText(`时间: ${getCurrentDateTime()}`, 10, canvas.height - 120);
              account && ctx.fillText(`账号: ${account}`, 10, canvas.height - 20);
          
              // Compress the image
              compressImage(canvas).then((compressedBlob) => {
                const compressedFile = new File([compressedBlob], file.name, {
                  type: "image/jpeg",
                });
                const objectUrl = URL.createObjectURL(compressedBlob);
                resolve({ ffff: compressedFile, objectUrl });
              });
            }).catch(() => {
              resolve({ ffff: null, objectUrl: null });
            })
          } catch (error) {
            uni.getLocation({
              type: "wgs84",
              success: function (res) {
                const newLocation = transformFromWGS84ToGCJ02(
                  res.longitude,
                  res.latitude
                );
                lon = newLocation[0];
                lat = newLocation[1];
                getAddress(lat, lon).then((res) => {
                  let address = res;
                  console.log(address);
                  ctx.fillText(`经纬度: ${lon},${lat}`, 10, canvas.height - 320);
                  address &&
                    ctx.fillText(`地址: ${address}`, 10, canvas.height - 220);
                  time && ctx.fillText(`时间: ${getCurrentDateTime()}`, 10, canvas.height - 120);
                  account &&
                    ctx.fillText(`账号: ${account}`, 10, canvas.height - 20);
          
                  // Compress the image
                  compressImage(canvas).then((compressedBlob) => {
                    const compressedFile = new File([compressedBlob], file.name, {
                      type: "image/jpeg",
                    });
                    const objectUrl = URL.createObjectURL(compressedBlob);
                    resolve({ ffff: compressedFile, objectUrl });
                  });
                }).catch(() => {
                  resolve({ ffff: null, objectUrl: null });
                })
              },
            });
          }
        } else {
          uni.getLocation({
            type: "wgs84",
            success: function (res) {
              const newLocation = transformFromWGS84ToGCJ02(
                res.longitude,
                res.latitude
              );
              lon = newLocation[0];
              lat = newLocation[1];
              getAddress(lat, lon).then((res) => {
                let address = res;
                console.log(address);
                ctx.fillText(`经纬度: ${lon},${lat}`, 10, canvas.height - 320);
                address &&
                  ctx.fillText(`地址: ${address}`, 10, canvas.height - 220);
                time && ctx.fillText(`时间: ${getCurrentDateTime()}`, 10, canvas.height - 120);
                account &&
                  ctx.fillText(`账号: ${account}`, 10, canvas.height - 20);
                    
                // Compress the image
                compressImage(canvas).then((compressedBlob) => {
                  const compressedFile = new File([compressedBlob], file.name, {
                    type: "image/jpeg",
                  });
                  const objectUrl = URL.createObjectURL(compressedBlob);
                  resolve({ ffff: compressedFile, objectUrl });
                });
              }).catch(() => {
                resolve({ ffff: null, objectUrl: null });
              })
            },
          });
        }
        
      } else {
        time && ctx.fillText(`时间: ${getCurrentDateTime()}`, 10, canvas.height - 120);
        account && ctx.fillText(`账号: ${account}`, 10, canvas.height - 20);
        // Compress the image
        compressImage(canvas).then((compressedBlob) => {
          const compressedFile = new File([compressedBlob], file.name, {
            type: "image/jpeg",
          });
          const objectUrl = URL.createObjectURL(compressedBlob);
          resolve({ ffff: compressedFile, objectUrl });
        });
      }
    };
    img.onerror = (err) => {
      console.error("生成图片失败");
      resolve({ ffff: null, objectUrl: null });
    };
  });
};

export const getAddress = async (lat?: number, lon?: number) => {
  let add =
    (
      await jsonp("http://apis.map.qq.com/ws/geocoder/v1", {
        location: `${lat},${lon}`,
        key: KEY,
        output: "jsonp",
      })
    )["result"]["formatted_addresses"]["recommend"] || "";
  return add;
};
